<template>
	<view class="container">
		<uni-forms :rules="rules" :modelValue="formData" ref="form" validate-trigger="bind" err-show-type="undertext">
			<uni-forms-item name="clientId" required label="单位名称">
				<zxz-uni-data-select v-model="formData.clientId" filterable :localdata="clientOptions" @change="getAddressOptions(formData.clientId)">
				</zxz-uni-data-select>
			</uni-forms-item>
			<uni-forms-item name="mainClientName" required label="维保单位">
				<uni-easyinput type="text" :inputBorder="true" v-model="formData.mainClientName"
							   placeholder="请输入维保单位名称"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="userName" required label="维保人员">
				<uni-easyinput type="text" :inputBorder="true" v-model="formData.userName"
							   placeholder="请输入维保人员名称"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="address" required label="维保地址">
				<zxz-uni-data-select v-model="formData.address" filterable :localdata="addressOptions" @change="getInspectionOptions(formData.address)">
				</zxz-uni-data-select>
			</uni-forms-item>
			<uni-forms-item required label="当前定位">
				<view style="display: flex;text-align: center">
					<uni-easyinput class="readonly-field" type="text" v-model="nowAddrInfo.address"
								   placeholder="请重新获取定位"></uni-easyinput>
				</view>
			</uni-forms-item>
			<uni-forms-item name="inspectionId" label="巡检问题简述">
				<zxz-uni-data-select v-model="formData.inspectionId" filterable :localdata="inspectionOptions">
				</zxz-uni-data-select>
			</uni-forms-item>
			<uni-forms-item name="state" required label="维保状态">
				<zxz-uni-data-select v-model="formData.state" :localdata="stateOptions">
				</zxz-uni-data-select>
			</uni-forms-item>
			<uni-forms-item label="维保电话" required prop="telephone">
				<uni-easyinput placeholder="请输入维保电话" v-model="formData.telephone" type="text" :inputBorder="true" ></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item required name="dateTime" label="维保时间">
				<uni-datetime-picker timestamp v-model="formData.dateTime"></uni-datetime-picker>
			</uni-forms-item>
			<uni-forms-item name="information" required label="维保信息">
				<uni-easyinput type="text" :inputBorder="true" v-model="formData.information"
							   placeholder="请输入维保信息"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="informationPhoto" required label="维保图片">
				<UploadImage :uploadedImages="informationPhotoList" :uploadUrl="this.$baseUrl+'/api/files/upload'">
				</UploadImage>
			</uni-forms-item>
			<uni-forms-item name="resultTime" label="检查时间">
				<uni-datetime-picker timestamp v-model="formData.resultTime"></uni-datetime-picker>
			</uni-forms-item>
			<uni-forms-item name="result" label="检查结果">
				<uni-easyinput type="text" :inputBorder="true" v-model="formData.result"
							   placeholder="请输入检查结果"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="resultPhoto" label="检查图片">
				<UploadImage :uploadedImages="resultPhotoList" :uploadUrl="this.$baseUrl+'/api/files/upload'">
				</UploadImage>
			</uni-forms-item>
		</uni-forms>
		<button type="primary" @click="submit('form')">提交</button>
	</view>
</template>

<script>
	import { getLocation } from '../../common/globleJS/globle'
	import UploadImage from '@/common/component/UploadImage.vue';
	import request from '@/util/request';
	export default {
		components: {
			UploadImage
		},
		onLoad(options) {
			this.maintenanceStr = decodeURIComponent(options.maintenance);
			const maintenance = JSON.parse(this.maintenanceStr);
			this.formData.id = maintenance.id;
			this.formData.clientName = maintenance.clientName;
			this.formData.mainClientName = maintenance.mainClientName;
			this.formData.inspectionId = maintenance.inspectionId;
			this.formData.userName = maintenance.userName;
			this.formData.address = maintenance.address;
			this.formData.addrName = maintenance.addrName;
			this.formData.telephone = maintenance.telephone;
			this.formData.information = maintenance.information;
			this.formData.dateTime = maintenance.dateTime;
			this.formData.result = maintenance.result;
			this.formData.resultTime = maintenance.resultTime;
			this.formData.state = maintenance.state;
			this.formData.informationPhoto = maintenance.informationPhoto;
			this.formData.resultPhoto = maintenance.resultPhoto;
			this.initPhotoList()
			this.getAddressOptions(maintenance.clientId)
			this.getInspectionOptions(maintenance.address)
		},
		data() {
			return {
				nowAddrInfo:{
					address:"",
					latitude:0,
					longitude:0
				},
				clientOptions: [],
				addressOptions: [],
				resultPhotoList: [],
				informationPhotoList: [],
				clientAddressOptions: [],
				inspectionOptions: [],
				stateOptions: [{
					value: "0",
					text: "已维保"
				},
					{
						value: "1",
						text: "未维保"
					}
				],
				formData: {
					state: "0",
				},
				rules: {
					address: {
						rules: [{
							required: true,
							errorMessage: '请先选择单位名称'
						}
						]
					},
					state: {
						rules: [{
							required: true,
							errorMessage: '请选择维保状态'
						}
						]
					},
				}
			}
		},
		mounted() {
			this.getClientOptions();
			this.getLatitude()
		},
		methods: {
			// 距离判断
			distinctjudg(){
				if(this.nowAddrInfo.latitude==0){
					uni.showToast({
						icon:'error',
						title:"请先获取定位"
					})
					this.formData.address=""
					return
				}

				const addressInfo = {
					latitude:0,
					longitude:0
				}
				const addressId = this.formData.address
				console.log(addressId)
				console.log(this.clientAddressOptions)
				// 获取选择的位置的经纬度
				this.clientAddressOptions.forEach(item=>{
					if(item.id==addressId){
						addressInfo.latitude=item.latitude
						addressInfo.longitude=item.longitude
					}
				})
				const distance = this.getDistance(addressInfo.latitude, addressInfo.longitude, this.nowAddrInfo.latitude, this.nowAddrInfo.longitude);
				if (distance > 100) {
					console.log("距离超过100米");
					uni.showToast({
						icon:'error',
						title:"超出100米"
					})
					this.formData.address=""
				} else {
					console.log("距离未超过100米");

				}
			},
			//
			getDistance(lat1, lon1, lat2, lon2) {
				const rad = Math.PI / 180;
				const earthRadius = 6371e3; // 地球半径，单位为米

				const φ1 = lat1 * rad;
				const φ2 = lat2 * rad;
				const Δφ = (lat2 - lat1) * rad;
				const Δλ = (lon2 - lon1) * rad;

				const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
						Math.cos(φ1) * Math.cos(φ2) *
						Math.sin(Δλ / 2) * Math.sin(Δλ / 2);

				const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
				return earthRadius * c; // 返回距离，单位为米
			},
			// 获取当前位置
			async getLatitude() {
				let position = await getLocation()
				console.log(position)
				this.nowAddrInfo.latitude=position.latitude
				this.nowAddrInfo.longitude=position.longitude
				const addr = position.address
				this.nowAddrInfo.address = addr.province + addr.city + addr.district + addr.street + addr.streetNum + addr.poiName
			},
			initPhotoList() {
				this.resultPhotoList = this.formData.resultPhoto ? this.formData.resultPhoto.split(',').map(url => {
					return {url}
				}) : [];
				this.informationPhotoList = this.formData.informationPhoto ? this.formData.informationPhoto.split(',').map(url => {
					return {url}
				}) : [];
			},
			handlePhoto() {
				this.resultPhotoList.forEach((item,index)=>{
					if(index==0){
						this.formData.resultPhoto=item.url
					}else{
						this.formData.resultPhoto+=","+item.url
					}
				});
				this.informationPhotoList.forEach((item,index)=>{
					if(index==0){
						this.formData.informationPhoto=item.url
					}else{
						this.formData.informationPhoto+=","+item.url
					}
				})
			},
			getClientOptions() {
				let level = this.$store.state.userInfo.level;
				let organizationId = this.$store.state.userInfo.organization;
				let isAllClient = this.$store.state.userInfo.isAllClient;
				let clientIds;
				if (isAllClient === "1") {
					clientIds = this.$store.state.userInfo.clientIds;
				} else {
					clientIds = [];
				}
				request.get("/client/listbyName?organizationId=" + organizationId + "&level=" + level + "&isAllClient=" + isAllClient + "&clientIds=" + clientIds).then(res => {
					if (res.code === '200') {
						res.data.forEach(item => {
							this.clientOptions.push({
								value: item.id,
								text: item.name
							})
						})
					}
				})
			},
			getAddressOptions(clientId){
				this.formData.address = null;
				this.addressOptions = [];
				if(clientId !== null && clientId !== '' && clientId !== undefined){
					let level = this.$store.state.userInfo.level;
					let organizationId = this.$store.state.userInfo.organization;
					let isAllClient = "1";
					let clientIds = clientId;
					request.get("/inspect-addr-code/all?organizationId="+organizationId+"&level="+level+"&isAllClient="+isAllClient+"&clientIds="+clientIds).then(res=>{
						if (res.code === '200') {
							console.log(res.data)
							res.data.forEach(item => {
								this.addressOptions.push({
									value: item.id,
									text: item.addrName
								})
								this.clientAddressOptions.push({
									id:item.id,
									latitude:item.latitude,
									longitude:item.longitude
								})
							})
						}
					})
				}
			},
			getInspectionOptions(address){
				this.distinctjudg()
				this.formData.inspectionId = null;
				this.inspectionOptions = [];
				if(address !== null && address !== '' && address !== undefined){
					request.get("/record-inspection/all?address="+address).then(res=>{
						if (res.code === '200') {
							console.log(res.data)
							res.data.forEach(item => {
								this.inspectionOptions.push({
									value: item.id,
									text: item.hiddenDanger
								})
							})
						}
					})
				}
			},
			submit(ref) {
				this.handlePhoto()
				console.log(this.formData);
				this.$refs[ref].validateField(['address']).then(res => {
					request.post("/record-maintenance/edit", this.formData).then(res => {
						if (res.code === '200') {
							uni.showToast({
								title: "编辑成功",
								icon:'success',
								duration: 2000
							});
						} else {
							uni.showToast({
								title: "编辑失败",
								icon:'error',
								duration: 2000
							});
						}
					})
				}).catch(err => {
					console.log('err', err);
				})
			},
			//重置表单 。原生的组件input组件不能重置表单
			resetForm() {
				this.$refs.form.resetFields()
			},
			clearValidate(form, name) {
				if (!name) name = []
				this.$refs[form].clearValidate(name)
			}
		}
	}
</script>
<style scoped>
	.container {
		margin: 15px;
	}

	.uni-input-border {
		padding: 0 10px;
		height: 35px;
		width: 100%;
		font-size: 14px;
		color: #666;
		border: 1px #e5e5e5 solid;
		border-radius: 5px;
		box-sizing: border-box;
	}

	.readonly-field {
		background-color: #ebebeb; /* 只读字段背景色，提示用户不能修改 */
		pointer-events: none; /* 禁用点击事件 */
		cursor: not-allowed; /* 设置不可点击的光标样式 */
	}
</style>
